<template>
  <div class="comment-container">
    <div class="type-title">评论({{ commentList?.length }})</div>
    <div class="comment-list-warp">
      <div class="comment-item" v-for="item in commentList" :key="item.id">
        <div class="comment-info">
          <div class="user-info">
            <el-avatar
              :size="30"
              :src="
                getCommentUser(item.user_id)?.avatar
                  ? getCommentUser(item.user_id)?.avatar
                  : 'https://openim-1309784708.cos.ap-shanghai.myqcloud.com/4ce4fccbca32722fdd9d41acb48ef409.jpg'
              "
            />
            <span class="user-name">{{ getCommentUser(item.user_id)?.name }}</span>
          </div>
          <div class="time">{{ item.updated_at }}</div>
        </div>
        <div class="comment-content">
          <v-md-editor mode="preview" v-model="item.content"></v-md-editor>
        </div>
        <div class="comment-action">
          <!-- 点赞 -->
          <div class="issues-like">
            <div
              class="like-box"
              :style="{ color: getLikeColor(item) ? '#409eff' : '' }"
              @click.stop="handleClick(item)"
            >
              <i class="iconfont icon-31dianzan"></i>
              <span>{{ getLikeLength(item) }}</span>
            </div>
          </div>
          <!-- 后面增加该功能 -->
          <!-- <el-button text @click.stop="handleReply(item)"
            ><i class="iconfont icongis_shanchu"></i>回复</el-button
          > -->
          <el-button
            text
            type="danger"
            v-if="usePermission('issues.delete') || item.user_id === getUserInfo.id"
            @click.stop="handleDelete(item)"
            ><i class="iconfont icongis_shanchu"></i>删 除</el-button
          >
        </div>
      </div>
      <el-empty v-if="!commentList" description="暂无评论"></el-empty>
    </div>
    <div class="comment-input-warp">
      <div class="user-info-warp">
        <el-avatar :size="30" :src="getUserInfo?.avatar"></el-avatar>
      </div>
      <div class="input-warp">
        <el-form
          :ref="(el:object) => { formRef = el }"
          :model="formData"
          :rules="rules"
          @submit.native.prevent
        >
          <el-form-item label-width="0" label="" prop="content">
            <v-md-editor
              mode="edit"
              placeholder="请输入内容"
              v-model="formData.content"
              height="200px"
              :disabled-menus="[]"
              @upload-image="handleUploadImage"
            ></v-md-editor>
          </el-form-item>
        </el-form>

        <el-button color="#6C52EA" @click.stop="handleSubmit">发表</el-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'

// import { newCommentData, deleteCommentData } from '@/apis/issues/issues-comment'
import { getToken } from '@/utils/token-cache'
// import { IcommentList } from '@/views/issues/config/issues'
// import { newLikeData, editLikeData } from '@/apis/issues/issues-comment-like'

import Request from '@/apis/index'

import { store } from '@/store/issues'
import { storeToRefs } from 'pinia'
import { IcommentList, IlikeData } from '../../config/problems'
import {
  deleteCommentData,
  editLikeData,
  newCommentData,
  newLikeData
} from '@/apis/system/problems'
import { usePermission } from '@/hooks/usePermission'

const issueStore = store()

const props = defineProps({
  issuesData: {
    type: Object,
    default: () => {}
  }
})

const formData = ref({
  content: ''
})

const rules = {
  content: [{ required: true, message: '请输入评论', trigger: 'blur' }]
}

/**
 * @desc: 获取评论
 */
const commentList = ref<IcommentList[]>()
watch(
  () => props.issuesData,
  (newVal) => {
    commentList.value = newVal.comment
  },
  { immediate: true }
)

/**
 * @desc:获取评论人员信息
 * @param {Array} search 搜索
 */
const { userList } = storeToRefs(issueStore)
const getCommentUser = computed(() => (id: number) => {
  return userList.value.find((item) => {
    return item.id === id
  })
})

/**
 * @desc: 获取自己是否点赞
 * @param {*} item
 * @return {boolean}
 */
const getLikeColor = computed(() => (item: IcommentList) => {
  return item?.like_connect?.filter((item) => item.uid === getUserInfo.value.id)[0]?.is_status === 1
})

/**
 * @desc: 获取所以点赞的长度
 * @param {*} item
 * @return {number}
 */
const getLikeLength = computed(() => (item: IcommentList) => {
  return item?.like_connect?.filter((item) => {
    return item?.is_status === 1
  }).length
})

/**
 * @desc: 发布提交
 */
const emit = defineEmits(['send-refresh'])
const formRef = ref()
const handleSubmit = () => {
  if (formRef.value) {
    formRef.value.validate((valid: boolean) => {
      if (!valid) return
      const reqData = {
        content: formData.value.content,
        page_id: props.issuesData.id,
        user_id: getUserInfo.value.id
      }
      newCommentData(reqData)
        .then((res) => {
          if (!res) return
          formData.value.content = ''
          emit('send-refresh')
          ElMessage({
            type: 'success',
            message: '发布成功'
          })
        })
        .catch(() => {
          ElMessage('服务器内部错误')
        })
    })
  }
}

/**
 * 新增点赞
 */
const createNewLike = (item: IcommentList) => {
  let params = {
    uid: getUserInfo.value.id,
    comment_id: item.id,
    is_status: 1
  }
  newLikeData(params)
    .then((res) => {
      if (!res) return
      ElMessage.success('点赞成功！')
      emit('send-refresh')
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
}

/**
 * 修改点赞
 */
const editLike = (item: IlikeData, itemData: IcommentList) => {
  editLikeData(item)
    .then((res) => {
      if (!res) return
      countLikeNum.value = itemData.like_connect.filter((item) => {
        return item.is_status === 1
      })
      switch (res.is_status) {
        case 1:
          ElMessage.success('点赞成功！')
          break
        case 0:
          ElMessage.error('已取消点赞！')
      }
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
}

/**
 *
 * @desc:获取登录用户信息
 */
const getUserInfo = computed(() => {
  return JSON.parse(localStorage.getItem('user') as string) || ''
})

/**
 * @desc: 点赞
 * @return {*}
 */
const findUserLike = ref<IlikeData>()
const countLikeNum = ref<IlikeData[]>()
const handleClick = (item: IcommentList) => {
  findUserLike.value = item?.like_connect?.find((item: IlikeData) => {
    return item.uid === getUserInfo.value.id
  })
  countLikeNum.value = item?.like_connect?.filter((item) => {
    return item.is_status === 1
  })
  if (!!findUserLike.value) {
    findUserLike.value.is_status = findUserLike.value.is_status === 0 ? 1 : 0
    editLike(findUserLike.value, item)
  } else {
    createNewLike(item)
  }
}

/**
 * @desc: 删除评论
 */
const handleDelete = (item: IcommentList) => {
  deleteCommentData(item.id)
    .then((res) => {
      if (!res) return
      emit('send-refresh')
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
}

/**
 * @desc: 图片上传
 */
const baseUrl = 'https://dwh_api.bimcc.net'
const handleUploadImage = (event: any, insertImage: any, files: any) => {
  return new Promise((reslove, resject) => {
    const data = new FormData()
    for (let i in files) {
      data.append('file', files[i])
    }
    Request.post({
      url: `${baseUrl}/api/mapi?__method_name__=file` + '&token=' + getToken(),
      data: data
    }).then((res) => {
      if (res && res.data.url) {
        insertImage({
          url: res.data.url,
          desc: res.data.filename,
          width: 'auto',
          height: 'auto'
        })
        reslove(res.data.url.replace('_thumb', ''))
      } else {
        resject('上传失败')
      }
    })
  })
}
</script>
<style lang="less" scoped>
.comment-container {
  width: 100%;
  height: auto;
  padding: 0 10px;
  box-sizing: border-box;
  .type-title {
    font-size: 1.2em;
    padding: 10px 0;
  }
  .comment-list-warp {
    width: 100%;
    height: auto;
    .comment-item {
      padding-bottom: 12px;
      border-bottom: 1px solid #f1f1f1;
      .comment-info {
        display: flex;
        align-items: center;
        height: 40px;
        justify-content: space-between;
        .user-info {
          display: flex;
          align-items: center;
          padding: 0 10px;
          .user-name {
            margin-left: 10px;
          }
        }
        .time {
          color: #999;
        }
      }
      .comment-content {
        height: auto;
        // max-width: 1052px;
        padding: 10px 0 10px 52px;

        :deep(.github-markdown-body) {
          padding: 0;
        }
      }
      .comment-action {
        // max-width: 1052px;
        display: flex;
        align-items: center;
        padding: 0px 0 0px 52px;
        .issues-like {
          display: flex;
          align-items: center;
          .like-box {
            line-height: 22px;
            padding-right: 20px;
            padding-left: 2px;
            transition: all ease 0.05s;
            &:hover {
              color: #409eff;
              transform: scale(1.1);
            }
            .icon-31dianzan {
              font-size: 18px;
              line-height: 22px;
              padding-right: 3px;
            }
          }
        }
      }
    }
  }
  .comment-input-warp {
    width: 100%;
    display: flex;
    .user-info-warp {
      padding: 10px;
      box-sizing: border-box;
    }
    .input-warp {
      flex-grow: 1;
      // max-width: 1000px;
    }
  }
  .no-auth-tips {
    padding: 20px;
    box-sizing: border-box;
    .info {
      display: flex;
      padding: 10px;
    }
  }
}
</style>
